<?php defined('SYSPATH') or die('No direct script access.');

// URL: /<context>/index.php/Home/
class Controller_Project extends Controller_Base 
{
	protected $profileService;
	protected $categoryService;
	
	protected $app_id = "YOUR_APP_ID";
	protected $app_secret = "YOUR_APP_SECRET";
	protected $my_url = "http://www.seednia.com/index.php/profile_fb/response";
	
	public function __construct(Request $request, Response $response)
	{
		parent::__construct($request, $response);
		$this->profileService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_PROFILE.'/', 'ns1.ProfileDto');
		$this->profileService->setAccessToken('seedniaPhpUi');
		$this->profileService->init($this->_sessionInfo);
		
		$this->categoryService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/CategoryServiceRest/', 'ns1.CategoryDto');
		$this->categoryService->setAccessToken('seedniaPhpUi');
		$this->categoryService->init($this->_sessionInfo);
	}
	
	public function action_index()
	{
		session_start();
		$code = $_REQUEST["code"];

		if(empty($code)) {
			$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
			$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=" 
				. $app_id . "&redirect_uri=" . urlencode($this->my_url) . "&state="
				. $_SESSION['state'];

			echo("<script> top.location.href='" . $dialog_url . "'</script>");
		}

		if($_REQUEST['state'] == $_SESSION['state']) {
			$token_url = "https://graph.facebook.com/oauth/access_token?"
				. "client_id=" . $this->app_id . "&redirect_uri=" . urlencode($my_url)
				. "&client_secret=" . $this->app_secret . "&code=" . $code;

			$response = file_get_contents($token_url);
			$params = null;
			parse_str($response, $params);

			$graph_url = "https://graph.facebook.com/me?access_token=" 
				. $params['access_token'];

			$user = json_decode(file_get_contents($graph_url));
			echo("Hello " . $user->name);
		}
		else {
			echo("The state does not match. You may be a victim of CSRF.");
		}

	}
	
	public function action_add()
	{
		if ($this->request->method() == "GET") {
			$this->showForm();
		} else if ($this->request->method() == "POST") {
			$this->doAdd();
		}
	}
	
	private function loadFormParams()
	{
		$creatorSid = $this->_sessionInfo->userInfo['userSid'];
		$categorySid = $this->request->post('categorySid');
		$name = $this->request->post('name');
		$goal = $this->request->post('goal');
		$description = $this->request->post('description');
		// TODO: Change below
		$planStartDate = '2012-11-10T09:08:07';//$this->request->post('planStartDate');
		$planEndDate = '2012-13-12T011:10:09';//$this->request->post('planEndDate');
		$tagNamesCsv = $this->request->post('tagNamesCsv');

		$params = array('creatorSid'=>$creatorSid
			, 'categorySid' => $categorySid, 'name'=>$name, 'goal'=>$goal, 'description'=>$description
			, 'planStartDate' => $planStartDate, 'planEndDate' => $planEndDate
			, 'tagNamesCsv' => $tagNamesCsv);
		return $params;
	}
	
} // End Controller_Home